<template>
  <div class="claim-calculation-container">
    <!-- 页面标题与返回按钮 -->
    <el-page-header :content="pageTitle" @back="handleBack" class="page-header" />

    <!-- 错误提示区域 -->
    <el-alert v-if="errorMsg" :message="errorMsg" type="error" show-icon closable @close="errorMsg = ''"
      style="margin-bottom: 16px" />

    <el-card shadow="hover" class="main-card">
      <!-- 1. 已立案报案列表（状态为4） -->
      <div v-if="showCaseList">
        <el-table :data="registeredCaseList" v-loading="listLoading" border size="small"
          @row-click="selectRegisteredCase" :row-class-name="tableRowClassName" empty-text="暂无已立案数据">
          <el-table-column prop="reportNo" label="报案号" min-width="180" />
          <el-table-column prop="policyId" label="保单编号" min-width="160" />
          <el-table-column prop="insuredId" label="投保人ID" min-width="120" />
          <el-table-column prop="reporterName" label="报案人" min-width="120" />
          <el-table-column label="报案状态" min-width="120">
            <template #default="scope">
              <el-tag type="success">{{ getReportStatus(scope.row.reportStatus) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="handleTime" label="受理时间" min-width="250">
            <template #default="scope">{{ formatDateTime(scope.row.handleTime) }}</template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="120">
            <template #default="scope">
              <el-button type="primary" size="small" @click="startCalculation(scope.row)">
                开始理算
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <div style="display:flex; justify-content:center; margin-top:12px;">
          <el-pagination background layout="prev, pager, next, jumper, ->, total, sizes"
            :page-size="pagination.pageSize" :current-page="pagination.pageNum" :page-sizes="[5, 10, 20, 50]"
            :total="pagination.total" @size-change="onPageSizeChange" @current-change="onPageChange" />
        </div>
      </div>

      <!-- 2. 理算表单区域 -->
      <div v-else>
        <!-- 返回列表按钮 -->
        <div style="display:flex; justify-content:flex-end; margin-bottom:15px;">
          <el-button @click="backToCaseList" type="success">返回列表</el-button>
        </div>

        <!-- 面板批量操作按钮 -->
        <div class="panel-controls" style="margin-bottom: 16px; display: flex; gap: 8px;">
          <el-button type="primary" size="small" @click="toggleAllPanels(true)" :icon="Expand">
            全部展开
          </el-button>
          <el-button type="primary" size="small" @click="toggleAllPanels(false)" :icon="Collapse">
            全部折叠
          </el-button>
        </div>

        <!-- 数据概览区域（四个面板统一控制） -->
        <el-collapse class="info-collapse" v-model="activePanels" @change="handlePanelChange">
          <el-collapse-item title="报案基本信息" name="report">
            <el-descriptions column="1" border>
              <el-descriptions-item label="报案号">{{ reportInfo.reportNo }}</el-descriptions-item>
              <el-descriptions-item label="保单编号">{{ reportInfo.policyId }}</el-descriptions-item>
              <el-descriptions-item label="投保人ID">{{ reportInfo.insuredId }}</el-descriptions-item>
              <el-descriptions-item label="报案人">{{ reportInfo.reporterName }}</el-descriptions-item>
              <el-descriptions-item label="联系电话">{{ reportInfo.reporterPhone }}</el-descriptions-item>
              <el-descriptions-item label="灾祸类型">{{ getDisasterType(reportInfo.disasterType) }}</el-descriptions-item>
              <el-descriptions-item label="灾祸发生时间">{{ formatDateTime(reportInfo.disasterOccurTime)
              }}</el-descriptions-item>
              <el-descriptions-item label="损失情况描述">{{ reportInfo.lossDescription }}</el-descriptions-item>
              <el-descriptions-item label="农户预估损失(元)">{{ formatCurrency(reportInfo.lossEstimate)
              }}</el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>

          <el-collapse-item title="立案信息" name="registration" v-if="calculationForm.registrationId">
            <el-descriptions column="1" border>
              <el-descriptions-item label="立案ID">{{ calculationForm.registrationId }}</el-descriptions-item>
              <el-descriptions-item label="关联报案号">{{ calculationForm.reportNo }}</el-descriptions-item>
              <el-descriptions-item label="立案状态">
                <el-tag type="success">已立案</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="备注">该案件已完成立案，可正常进行理算</el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>

          <el-collapse-item title="保单信息" name="policy">
            <el-descriptions column="1" border v-if="policyInfo.policyId">
              <el-descriptions-item label="保单编号">{{ policyInfo.policyId }}</el-descriptions-item>
              <el-descriptions-item label="投保人姓名">{{ policyInfo.insuredName || policyInfo.insuredId
              }}</el-descriptions-item>
              <el-descriptions-item label="保险标的">{{ policyInfo.insuranceSubject }}</el-descriptions-item>
              <el-descriptions-item label="保险金额(元)">{{ formatCurrency(policyInfo.sumInsured) }}</el-descriptions-item>
              <el-descriptions-item label="保险期间">{{ formatDate(policyInfo.startDate) }} 至 {{
                formatDate(policyInfo.endDate)
              }}</el-descriptions-item>
              <el-descriptions-item label="保险费(元)">{{ formatCurrency(policyInfo.totalPremium) }}</el-descriptions-item>
              <el-descriptions-item label="缴费状态">{{ getPayStatus(policyInfo.payStatus) }}</el-descriptions-item>
              <el-descriptions-item label="保单状态">{{ getPolicyStatus(policyInfo.policyStatus) }}</el-descriptions-item>
            </el-descriptions>
            <div v-else class="empty-info">
              暂无保单信息，请检查保单编号是否正确
            </div>
          </el-collapse-item>

          <el-collapse-item title="查勘信息" name="survey">
            <!-- 查勘记录选择器（新增） -->
            <div v-if="surveyList.length > 0" style="margin-bottom: 16px;">
              <el-label style="margin-right: 8px; font-weight: 500;">选择查勘记录：</el-label>
              <el-select v-model="selectedSurveyId" placeholder="请选择查勘记录" @change="handleSurveyChange"
                style="width: 300px;">
                <el-option v-for="survey in surveyList" :key="survey.surveyId"
                  :label="`查勘ID：${survey.surveyId}（${formatDateTime(survey.surverEndTime || survey.createTime)}）`"
                  :value="survey.surveyId" />
              </el-select>
            </div>

            <!-- 查勘详情展示 -->
            <el-descriptions column="1" border v-if="selectedSurvey">
              <el-descriptions-item label="查勘表ID">{{ selectedSurvey.surveyId }}</el-descriptions-item>
              <el-descriptions-item label="查勘员">{{ selectedSurvey.surveyInWorkNo || selectedSurvey.surveyOutWorkNo ||
                '未指定'
              }}</el-descriptions-item>
              <el-descriptions-item label="查勘损失类型">{{ getLossType(selectedSurvey.lossType) }}</el-descriptions-item>
              <el-descriptions-item label="受灾面积">{{ selectedSurvey.disasterArea ? `${selectedSurvey.disasterArea} 亩` :
                '未填写'
              }}</el-descriptions-item>
              <el-descriptions-item label="查勘照片">
                <div v-if="selectedSurvey.surveyPhoto && selectedSurvey.surveyPhoto.trim()" class="survey-photo-list">
                  <el-image v-for="(photo, idx) in selectedSurvey.surveyPhoto.split(',').filter(item => item.trim())"
                    :key="idx" :src="photo" style="width: 120px; height: 120px; margin-right: 12px; margin-bottom: 12px"
                    :preview-src-list="selectedSurvey.surveyPhoto.split(',').filter(item => item.trim())"
                    :initial-index="idx" fit="cover" :alt="`查勘现场照片 ${idx + 1}`" />
                </div>
                <span v-else>无照片</span>
              </el-descriptions-item>
              <el-descriptions-item label="查勘结论">{{ selectedSurvey.disasterReason || '无' }}</el-descriptions-item>
              <el-descriptions-item label="查勘地址">{{ selectedSurvey.surveyAddress || '未填写' }}</el-descriptions-item>
              <el-descriptions-item label="查勘状态">{{ getSurveyStatus(selectedSurvey.surveyStatus)
              }}</el-descriptions-item>
            </el-descriptions>
            <div v-else class="empty-info">
              暂无查勘信息
            </div>
          </el-collapse-item>
        </el-collapse>

        <!-- 理算表单 -->
        <el-form ref="calculationFormRef" :model="calculationForm" label-width="160px" :rules="formRules"
          class="calculation-form" :disabled="formDisabled" style="margin-top: 20px">
          <!-- 1. 数据库主键与关联字段 -->
          <el-form-item label="理算唯一ID" prop="calculationId">
            <el-input v-model="calculationForm.calculationId" readonly placeholder="自动生成：CALC+日期+6位序列号" />
          </el-form-item>

          <el-form-item label="报案号" prop="reportNo" required>
            <el-input v-model="calculationForm.reportNo" readonly />
          </el-form-item>

          <el-form-item label="立案ID" prop="registrationId" required>
            <el-input v-model="calculationForm.registrationId" readonly />
            <div class="el-form-item__help">
              <span v-if="calculationForm.registrationId" class="text-success">✓ 已获取立案信息</span>
              <span v-else class="text-warning">! 未获取到立案信息，可能导致提交失败</span>
            </div>
          </el-form-item>

          <el-form-item label="保单编号" prop="policyId" required>
            <el-input v-model="calculationForm.policyId" readonly />
          </el-form-item>

          <el-form-item label="投保人ID" prop="insuredId" required>
            <el-input v-model="calculationForm.insuredId" readonly />
          </el-form-item>

          <el-form-item label="理算员ID" prop="calculatorId" required>
            <el-select v-model="calculationForm.calculatorId" placeholder="请选择理算员" clearable filterable>
              <el-option v-for="item in adjusterOptions" :key="item.workNo"
                :label="`${item.realName}（工号：${item.workNo}）`" :value="item.workNo" />
            </el-select>
          </el-form-item>

          <!-- 2. 核心计算字段 -->
          <el-form-item label="保险金额(元)" prop="sumInsured" required>
            <el-input v-model.number="calculationForm.sumInsured" type="number" step="0.01" readonly />
            <div class="el-form-item__help">取自投保单表，作为赔付金额计算基数</div>
          </el-form-item>

          <el-form-item label="赔付率(%)" prop="lossRate" required>
            <el-input v-model.number="calculationForm.lossRate" type="number" step="0.01" @input="calculateLossAmount"
              placeholder="手动输入赔付率（如80.00表示80%）" />
            <div class="el-form-item__help">范围：0-100，手动填写后自动计算赔付金额</div>
          </el-form-item>

          <el-form-item label="赔付金额(元)" prop="lossAmount" required>
            <el-input v-model.number="calculationForm.lossAmount" type="number" step="0.01" readonly />
            <div class="el-form-item__help">计算规则：保险金额 × 赔付率 ÷ 100（自动生成，不可编辑）</div>
          </el-form-item>

          <!-- 3. 文本字段 -->
          <el-form-item label="理算依据" prop="calculationBasis" required>
            <el-input v-model="calculationForm.calculationBasis" type="textarea" rows="2"
              placeholder="如：保单条款第5条、农业保险条例第X款" />
          </el-form-item>

          <el-form-item label="理算备注" prop="calculationRemark">
            <el-input v-model="calculationForm.calculationRemark" type="textarea" rows="3"
              placeholder="特殊情况说明（如赔付率调整原因）" />
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item class="form-actions">
            <el-button @click="handleReset" :disabled="formDisabled">重置</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
              提交理算结果
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading, ElLabel } from 'element-plus'
import hxxp from '@/utils/hxxp.js'
const router = useRouter()

// 错误提示变量
const errorMsg = ref('')

// 页面状态
const pageTitle = ref('保险理算管理')
const showCaseList = ref(true)
const listLoading = ref(false)
const submitLoading = ref(false)
const formDisabled = ref(false)
const calculationFormRef = ref(null)

// 分页配置
const pagination = reactive({
  pageNum: 1,
  pageSize: 5,
  total: 0
})

// 数据存储
const registeredCaseList = ref([])
const reportInfo = reactive({})
const policyInfo = reactive({})
const surveyList = ref([])
const selectedSurvey = ref(null)
const selectedSurveyId = ref('') // 新增：用于绑定查勘记录选择器
const adjusterOptions = ref([])

// 理算表单数据
const calculationForm = reactive({
  calculationId: '', // 理算唯一ID（主键）
  reportNo: '', // 报案号
  registrationId: '', // 立案ID（唯一约束，后端必填）
  policyId: '', // 保单编号
  insuredId: '', // 投保人ID
  calculatorId: '', // 理算员ID
  sumInsured: 0, // 保险金额（数字类型）
  lossRate: 0, // 赔付率（数字类型）
  lossAmount: 0, // 赔付金额（数字类型）
  calculationBasis: '', // 理算依据
  calculationRemark: '' // 理算备注
})

// 表单验证规则
const formRules = reactive({
  calculationId: [
    { required: true, message: '理算ID不能为空', trigger: 'blur' }
  ],
  reportNo: [
    { required: true, message: '报案号不能为空', trigger: 'blur' }
  ],
  registrationId: [
    { required: true, message: '立案ID不能为空（请确保案件已立案）', trigger: 'blur' },
    { min: 1, max: 32, message: '立案ID长度需在1-32字符之间', trigger: 'blur' }
  ],
  policyId: [
    { required: true, message: '保单编号不能为空', trigger: 'blur' }
  ],
  insuredId: [
    { required: true, message: '投保人ID不能为空', trigger: 'blur' }
  ],
  calculatorId: [
    { required: true, message: '请选择理算员', trigger: 'change' }
  ],
  sumInsured: [
    { required: true, message: '保险金额不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === '' || value === null || value === undefined) {
          callback();
          return;
        }
        const numValue = Number(value);
        if (isNaN(numValue)) {
          callback(new Error('保险金额必须为有效数字'));
          return;
        }
        if (numValue <= 0.01) {
          callback(new Error('保险金额必须大于0（最小0.01元）'));
          return;
        }
        const valueStr = String(value);
        const decimalPart = valueStr.split('.')[1];
        if (decimalPart && decimalPart.length > 2) {
          callback(new Error('保险金额最多保留2位小数'));
          return;
        }
        callback();
      },
      trigger: 'blur'
    }
  ],
  lossRate: [
    { required: true, message: '请填写赔付率', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '赔付率必须在0-100之间', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && String(value).split('.').length > 2) {
          callback(new Error('赔付率最多保留2位小数'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ],
  lossAmount: [
    { required: true, message: '赔付金额不能为空', trigger: 'blur' },
    { type: 'number', min: 0, message: '赔付金额不能为负数', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value > calculationForm.sumInsured) {
          callback(new Error(`赔付金额不能超过保险金额（当前保额：${calculationForm.sumInsured}元）`));
        } else if (value && String(value).split('.').length > 2) {
          callback(new Error('赔付金额最多保留2位小数'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ],
  calculationBasis: [
    { required: true, message: '请填写理算依据', trigger: 'blur' },
    { min: 10, message: '理算依据需至少10个字符', trigger: 'blur' }
  ]
})

// ---------------------- 3. 面板折叠控制（统一管理） ----------------------
// 所有面板的唯一标识
const panelKeys = ['report', 'registration', 'policy', 'survey']

// 折叠面板状态（初始为空数组，所有面板默认折叠）
const activePanels = ref([])

/**
 * 统一控制所有面板的折叠/展开状态
 * @param {boolean} expand - true:全部展开, false:全部折叠
 */
const toggleAllPanels = (expand) => {
  if (expand) {
    // 过滤掉不存在的面板（如立案信息可能不存在）
    const validPanels = panelKeys.filter(key => {
      // 特殊处理：立案信息面板可能不存在（v-if控制）
      if (key === 'registration') {
        return !!calculationForm.registrationId
      }
      return true
    })
    activePanels.value = [...validPanels]
  } else {
    activePanels.value = []
  }
}

/**
 * 监听面板状态变化
 * @param {Array} newActivePanels - 最新的激活面板列表
 */
const handlePanelChange = (newActivePanels) => {
  console.log('面板状态变化:', newActivePanels)
}

// ---------------------- 4. 字典映射 ----------------------
const reportStatusMap = {
  1: '待调度',
  2: '待查勘',
  3: '待立案',
  4: '已立案',
  5: '待理算',
  6: '待核赔',
  7: '待结案',
  8: '已结案',
  9: '已驳回'
}
const disasterTypeMap = { 1: '暴雨', 2: '洪水', 3: '病虫害', 4: '疫病', 5: '其他' }
const lossTypeMap = { 1: '作物', 2: '牲畜', 3: '农机', 4: '其他' }
const policyStatusMap = { 1: '待生效', 2: '已生效', 3: '已退保', 4: '已过期' }
const payStatusMap = { 1: '待缴费', 2: '缴费中', 3: '缴费成功', 4: '缴费失败' }
const surveyStatusMap = { 1: '待查勘', 2: '查勘中', 3: '已完成', 4: '已驳回' }

// 字典文本获取
const getReportStatus = (value) => reportStatusMap[value] || '未知'
const getDisasterType = (value) => disasterTypeMap[value] || '未知'
const getLossType = (value) => lossTypeMap[value] || '未知'
const getPolicyStatus = (value) => policyStatusMap[value] || '未知'
const getPayStatus = (value) => payStatusMap[value] || '未知'
const getSurveyStatus = (value) => surveyStatusMap[value] || '未知'

// ---------------------- 5. 工具函数 ----------------------
// 金额格式化（保留2位小数）
const formatCurrency = (value) => {
  if (!value && value !== 0) return '0.00'
  return Number(value).toFixed(2)
}

// 日期时间格式化
const formatDateTime = (value) => {
  if (!value) return '未填写'
  const date = new Date(value)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}

// 日期格式化
const formatDate = (value) => {
  if (!value) return '未填写'
  const date = new Date(value)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 生成理算唯一ID（主键）
const generateCalculationId = () => {
  const date = new Date()
  const dateStr = `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}`; // YYYYMMDD
  const randomStr = Math.floor(Math.random() * 1000000).toString().padStart(6, '0'); // 6位序列号
  return `CALC${dateStr}${randomStr}`;
}

// 表格行样式
const tableRowClassName = ({ row }) => {
  return 'cursor-pointer'
}

// ---------------------- 6. 数据获取方法 ----------------------
// 获取已立案报案列表
const fetchRegisteredCases = async () => {
  try {
    listLoading.value = true
    const { pageNum, pageSize } = pagination
    const res = await hxxp.get('/aiClaimReport/all', {
      params: {
        pageNum,
        pageSize,
        reportStatus: 4 // 只查询已立案的报案
      }
    })

    if (res.code === 100200) {
      const pageData = res.data || { list: [], total: 0 }
      registeredCaseList.value = Array.isArray(pageData.list) ? pageData.list : []
      pagination.total = Number(pageData.total || 0)
    } else {
      registeredCaseList.value = []
      pagination.total = 0
      ElMessage.error(res.msg || '获取已立案列表失败')
    }
  } catch (e) {
    console.error('获取已立案列表失败:', e)
    registeredCaseList.value = []
    pagination.total = 0
    ElMessage.error('网络异常，获取已立案列表失败')
  } finally {
    listLoading.value = false
  }
}

// 获取理算员列表
const getAdjusterList = async () => {
  try {
    const response = await hxxp.get('/aiStaffUser/worker', {
      params: {
        positionCode: 'PTN007' // 理算员职位编码
      }
    })

    if (response.code === 100200) {
      adjusterOptions.value = (response.data || []).map(staff => ({
        workNo: staff.workNo,
        realName: staff.realName
      }))

      if (adjusterOptions.value.length === 0) {
        ElMessage.warning('当前无可用理算员，请联系管理员配置')
      }
    } else {
      ElMessage.error(`获取理算员列表失败：${response.msg || '未知错误'}`)
      adjusterOptions.value = []
    }
  } catch (error) {
    console.error('获取理算员列表失败:', error)
    ElMessage.error('获取理算员列表失败，请检查网络')
    adjusterOptions.value = []
  }
}

// 获取保单信息
const fetchPolicyInfo = async (policyId) => {
  try {
    const res = await hxxp.get('/aiInsureOrder/getOrder', {
      params: { policyId }
    })

    if (res && res.policyId) {
      Object.assign(policyInfo, res);
      policyInfo.sumInsured = Number(res.sumInsured).toFixed(2);
      return true
    } else {
      ElMessage.warning(`未查询到保单号为${policyId}的保单信息`)
      return false
    }
  } catch (e) {
    console.error('获取保单信息失败:', e)
    ElMessage.error('获取保单信息失败，请重试')
    return false
  }
}

// 获取报案详情
const fetchReportInfo = async (reportNo) => {
  try {
    const res = await hxxp.get(`/aiClaimReport/${reportNo}`)
    if (res.code === 100200 && res.data) {
      Object.assign(reportInfo, res.data)
      return true
    } else {
      ElMessage.warning('未查询到报案信息')
      return false
    }
  } catch (e) {
    console.error('获取报案信息失败:', e)
    ElMessage.error('获取报案信息失败，请重试')
    return false
  }
}

// 获取立案信息
const fetchRegistrationInfo = async (reportNo) => {
  try {
    const res = await hxxp.get(`/aiClaimRegistration/getByReportNo/${reportNo}`);
    if (res.code === 100200 && res.data) {
      calculationForm.registrationId = res.data.registrationId || '';
    } else {
      ElMessage.warning('未查询到立案信息，可能导致提交失败，请确认案件已立案');
      calculationForm.registrationId = '';
    }
  } catch (e) {
    console.error('获取立案信息失败:', e);
    ElMessage.warning('获取立案信息失败，请检查9000端口服务是否正常');
    calculationForm.registrationId = '';
  }
};

// 获取查勘信息（修改：支持多记录）
const fetchSurveyInfo = async (reportNo) => {
  try {
    if (!reportNo || typeof reportNo !== 'string' || reportNo.trim() === '') {
      ElMessage.error('报案号格式错误，无法获取查勘信息');
      return false;
    }

    const res = await hxxp.get(`/aiSurveyReport/${reportNo}`);

    if (res.code === 100200) {
      const surveyArray = res.data || [];

      if (Array.isArray(surveyArray) && surveyArray.length > 0) {
        // 按查勘结束时间倒序排序，最新记录在前
        const sortedSurveys = surveyArray.sort((s1, s2) => {
          return new Date(s2.surverEndTime || 0) - new Date(s1.surverEndTime || 0);
        });

        surveyList.value = sortedSurveys;
        // 默认选中第一条记录
        selectedSurvey.value = sortedSurveys[0];
        selectedSurveyId.value = sortedSurveys[0].surveyId;
        return true;

      } else {
        ElMessage.warning('当前案件暂无查勘记录，不影响理算（可手动填写赔付率）');
        surveyList.value = [];
        selectedSurvey.value = null;
        selectedSurveyId.value = '';
        return true;
      }

    } else {
      const errorMsg = res.msg || '获取查勘信息失败';
      ElMessage.error(errorMsg);
      surveyList.value = [];
      selectedSurvey.value = null;
      selectedSurveyId.value = '';
      return true;
    }

  } catch (e) {
    console.error('查勘接口调用异常：', e);
    ElMessage.warning('查勘信息加载失败，不影响理算（可手动填写赔付率）');
    surveyList.value = [];
    selectedSurvey.value = null;
    selectedSurveyId.value = '';
    return true;
  }
};

// ---------------------- 7. 业务操作方法 ----------------------
// 分页事件
const onPageChange = (page) => {
  pagination.pageNum = page
  fetchRegisteredCases()
}

const onPageSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  fetchRegisteredCases()
}

// 选择行事件
const selectRegisteredCase = (row) => {
  console.log('选中的报案信息:', row)
}

// 开始理算
const startCalculation = async (row) => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在加载相关数据...',
    background: 'rgba(255, 255, 255, 0.7)'
  });

  try {
    errorMsg.value = '';

    if (!row?.reportNo || !row?.policyId) {
      ElMessage.error('报案信息不完整（缺少报案号/保单编号），无法开始理算');
      return;
    }

    // 加载关联数据
    const reportSuccess = await fetchReportInfo(row.reportNo);
    if (!reportSuccess) return;

    const policySuccess = await fetchPolicyInfo(row.policyId);
    if (!policySuccess) return;

    await fetchRegistrationInfo(row.reportNo);
    await fetchSurveyInfo(row.reportNo);
    await getAdjusterList();

    // 填充表单
    fillCalculationForm();

    // 生成理算ID
    calculationForm.calculationId = generateCalculationId();

    // 切换视图
    showCaseList.value = false;
  } finally {
    loading.close();
  }
};

// 填充理算表单
const fillCalculationForm = () => {
  // 关联字段
  calculationForm.reportNo = reportInfo.reportNo || '';
  calculationForm.policyId = reportInfo.policyId || '';
  calculationForm.insuredId = reportInfo.insuredId || '';
  calculationForm.sumInsured = Number(policyInfo.sumInsured || 0).toFixed(2);

  // 计算字段默认值
  calculationForm.lossRate = 0;
  calculationForm.lossAmount = 0;

  // 文本字段清空
  calculationForm.calculationBasis = '';
  calculationForm.calculationRemark = '';
  calculationForm.calculatorId = '';
};

// 计算赔付金额
const calculateLossAmount = () => {
  try {
    const sumInsured = Number(calculationForm.sumInsured);
    const lossRate = Number(calculationForm.lossRate);

    if (isNaN(sumInsured) || isNaN(lossRate)) {
      ElMessage.error('计算参数格式错误，请输入有效数字');
      calculationForm.lossAmount = 0;
      return;
    }

    // 计算逻辑：赔付金额 = 保险金额 × 赔付率 ÷ 100
    let lossAmount = (sumInsured * lossRate) / 100;
    lossAmount = Number(lossAmount.toFixed(2));

    // 边界处理
    lossAmount = Math.max(lossAmount, 0);
    lossAmount = Math.min(lossAmount, sumInsured);

    calculationForm.lossAmount = lossAmount;
  } catch (e) {
    console.error('计算赔付金额失败:', e);
    ElMessage.error('计算赔付金额失败，请检查输入参数');
    calculationForm.lossAmount = 0;
  }
};

// 提交理算结果
const handleSubmit = async () => {
  if (!calculationFormRef.value) return;

  errorMsg.value = '';

  // 表单验证
  try {
    await calculationFormRef.value.validate();
  } catch (error) {
    ElMessage.error('表单验证失败，请检查标红字段');
    return;
  }

  // 二次确认
  ElMessageBox.confirm(
    '确定提交理算结果吗？提交后将无法修改。',
    '提交确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    submitLoading.value = true;
    const loading = ElLoading.service({
      lock: true,
      text: '正在提交理算结果...',
      background: 'rgba(255, 255, 255, 0.7)'
    });

    try {
      // 提交数据
      const submitData = {
        calculationId: calculationForm.calculationId,
        reportNo: calculationForm.reportNo,
        registrationId: calculationForm.registrationId,
        policyId: calculationForm.policyId,
        insuredId: calculationForm.insuredId,
        calculatorId: calculationForm.calculatorId,
        sumInsured: Number(calculationForm.sumInsured),
        lossRate: Number(calculationForm.lossRate),
        lossAmount: Number(calculationForm.lossAmount),
        calculationBasis: calculationForm.calculationBasis,
        calculationRemark: calculationForm.calculationRemark
      };

      // 打印提交数据（便于调试）
      console.log('提交理算数据:', submitData);

      // 提交到后端
      const res = await hxxp.post('/aiClaimCalculation/addAdjustment', submitData);

      if (res.code === 100200) {
        ElMessage.success(`理算结果提交成功！赔付金额：${submitData.lossAmount.toFixed(2)}元`);
        backToCaseList();
      } else {
        ElMessage.error(`提交失败：${res.msg || '未知错误'}`);
      }
    } catch (e) {
      console.error('提交理算结果失败:', e);
      errorMsg.value = `提交失败：${e.message || '网络异常'}`;
    } finally {
      submitLoading.value = false;
      loading.close();
    }
  }).catch(() => {
    ElMessage.info('已取消提交');
  });
};

// 重置表单
const handleReset = () => {
  if (calculationFormRef.value) {
    calculationFormRef.value.resetFields();
    calculationForm.calculationId = generateCalculationId();
    // 重置面板状态（保持当前折叠/展开状态）
  }
};

// 返回列表页
const backToCaseList = () => {
  // 清空表单数据
  Object.keys(calculationForm).forEach(key => {
    if (['sumInsured', 'lossRate', 'lossAmount'].includes(key)) {
      calculationForm[key] = 0;
    } else {
      calculationForm[key] = '';
    }
  });

  // 清空关联数据
  Object.keys(reportInfo).forEach(key => reportInfo[key] = '');
  Object.keys(policyInfo).forEach(key => policyInfo[key] = '');
  surveyList.value = [];
  selectedSurvey.value = null;
  selectedSurveyId.value = ''; // 清空查勘选择器
  adjusterOptions.value = [];

  // 重置面板状态（列表页使用）
  activePanels.value = ['report', 'policy', 'survey'];
  errorMsg.value = '';

  // 切换视图并刷新列表
  showCaseList.value = true;
  fetchRegisteredCases();
};

// 返回上一页
const handleBack = () => {
  router.back();
};

// 新增：切换查勘记录
const handleSurveyChange = (surveyId) => {
  const matchedSurvey = surveyList.value.find(item => item.surveyId === surveyId)
  if (matchedSurvey) {
    selectedSurvey.value = matchedSurvey
  } else {
    selectedSurvey.value = null
    ElMessage.warning('未找到对应的查勘记录')
  }
}

// ---------------------- 8. 监听与初始化 ----------------------
// 监听赔付率变化，自动计算赔付金额
watch(() => calculationForm.lossRate, (newVal) => {
  if (newVal !== null && newVal !== undefined && !isNaN(Number(newVal)) && Number(calculationForm.sumInsured) > 0) {
    calculateLossAmount();
  }
});

// 页面加载时初始化
onMounted(() => {
  fetchRegisteredCases();
});

// 组件卸载前清理
onBeforeUnmount(() => {
  registeredCaseList.value = [];
  Object.keys(reportInfo).forEach(key => reportInfo[key] = '');
  Object.keys(policyInfo).forEach(key => policyInfo[key] = '');
  surveyList.value = [];
  selectedSurvey.value = null;
  selectedSurveyId.value = ''; // 清理查勘选择器状态
  Object.keys(calculationForm).forEach(key => calculationForm[key] = '');
  adjusterOptions.value = [];
});
</script>

<style scoped>
.claim-calculation-container {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
  background-color: #fafafa;
  min-height: calc(100vh - 120px);
}

.page-header {
  margin-bottom: 24px;
}

.main-card {
  background-color: #fff;
  padding: 32px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

/* 错误提示样式 */
.el-alert {
  margin-bottom: 16px;
}

/* 列表区域样式 */
.el-table {
  margin-bottom: 16px;
}

.el-table__row:hover>td {
  background-color: #f0f7ff !important;
}

/* 面板控制按钮样式 */
.panel-controls {
  padding: 8px 0;
  border-bottom: 1px solid #f1f3f4;
}

/* 数据概览区域样式 */
.info-collapse {
  margin-bottom: 24px;
  border: 1px solid #f1f3f4;
  border-radius: 8px;
  overflow: hidden;
}

.el-collapse-item__header {
  background-color: #f8f9fa;
  font-weight: 500;
}

.el-collapse-item__content {
  padding: 20px;
}

.empty-info {
  text-align: center;
  padding: 24px;
  color: #606266;
  background-color: #f9fafb;
  border-radius: 8px;
}

/* 查勘照片样式 */
.survey-photo-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 8px;
}

/* 查勘选择器样式 */
.el-label {
  color: #606266;
  font-size: 14px;
}

/* 理算表单样式 */
.calculation-form .el-form-item__help {
  color: #606266;
  font-size: 12px;
  margin-top: 4px;
}

/* 成功/警告文本样式 */
.text-success {
  color: #198754;
}

.text-warning {
  color: #ffc107;
}

.calculation-form .el-form-item.is-required .el-form-item__label::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

.el-form-item {
  margin-bottom: 28px;
}

.form-actions {
  margin-top: 40px;
  display: flex;
  justify-content: flex-end;
  gap: 16px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .claim-calculation-container {
    padding: 16px;
  }

  .main-card {
    padding: 16px;
  }

  .el-collapse-item__content {
    padding: 12px;
  }

  .el-form-item {
    margin-bottom: 20px;
  }

  .form-actions {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
